# -*- coding:utf-8 -*-
from __future__ import absolute_import
from django.shortcuts import render, render_to_response, redirect
from django.contrib.gis import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect,HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from ratelimit.decorators import ratelimit
from datakeeper.models import *
from datakeeper.utils import *
from weblib.django.setting import *
from .workers import *
from filecache.utils import *
import datasets.scripts.merra as merra
import datakeeper.indicator_view as indicator
import littler.little_r_utils.little_r_reader as lr

def help_page(request, topic=None):
    # raw_pages = {
    #     None: 'fengge/help.html',
    #     'about_datasets': 'fengge/about_datasets.html',
    #     'about_formats': 'fengge/about_formats.html',
    #     'about_register': 'fengge/about_register.html',
    #     'about_browser': 'fengge/about_browser.html',
    #     'project': 'fengge/project.html',
    #     'ui': 'fengge/ui.html',
    #     'map_feature': 'fengge/map_feature.html',
    #     'map_widget': 'fengge/map_widget.html',
    # }
    use_cab = get_setting('HELP_PAGE_USE_CAB', False)
    if use_cab:
        try:
            pass
            ##help_cab = Cabinet.objects.get(pk='help')
           # topic = topic.rstrip('/') if topic else 'help'
            #topic_ext = get_ext(topic)
            #if topic_ext == '':
            #    topic_file_path = '%s.html' % topic
            #else:
            #    topic_file_path = topic
           # #true_path = help_cab.get_file(topic_file_path)
           # return HttpResponse(open(true_path).read())
        except Exception as e:
            raise Http404
    else:
        if topic:
            topic = topic.rstrip('/')
            raw_page = 'help/%s.html' % topic
        else:
            raw_page = 'help/help.html'
        context = RequestContext(request, {'user': request.user, 'topic': topic})

        return render_to_response(raw_page, context)

def view(request, *args, **kwargs):
    return HttpResponseRedirect("/common/windpage/windsource.html")


def login_page(request):
    context = {}
    return render_to_response('user/login.html', context)



def per_day_data_rate(group, request):
    try:
        user_setting = UserDataSetting.objects.get(user=request.user)
    except UserDataSetting.DoesNotExist:
        return '100/d'

    if user_setting.data_limit_per_day < 0:
        return None
    else:
        return '%d/d' % user_setting.data_limit_per_day

@csrf_protect
def lookup_view(request, *args, **kwargs):
    return data_keeper.lookup_view(request, *args, **kwargs)

@csrf_protect
def data_view1(request, *args, **kwargs):
    merra.run()
    result_dict = {
                "status": "OK",
                "reason": "",
                "objects": 0
            }
    return JsonResponse(result_dict)
# @ratelimit(key='user', rate='1/1s', block=True)
@csrf_protect
#@ratelimit(key='user', rate=per_day_data_rate, block=True)
def data_view(request, uri, *args, **kwargs):
    return data_keeper.data_view(request, uri, *args, **kwargs)

# @ratelimit(key='user', rate='1/1s', block=True)
@csrf_protect
#@ratelimit(key='user', rate=per_day_data_rate, block=True)
def data_view_json(request, uri, *args, **kwargs):
    return data_keeper.data_view_json(request, uri, *args, **kwargs)

# @ratelimit(key='user', rate='1/1s', block=True)
@csrf_protect
#@ratelimit(key='user', rate=per_day_data_rate, block=True)
def data_view_schema(request, uri, *args, **kwargs):
    return data_keeper.data_view_schema(request, uri, *args, **kwargs)


# @ratelimit(key='user', rate='1/1s', block=True)
@csrf_protect
# @ratelimit(key='user', rate=per_day_data_rate, block=True)
def data_to_cvs_view(request, *args, **kwargs):
    return indicator.data_to_cvs_file(request, *args, **kwargs)


# @ratelimit(key='user', rate='1/1s', block=True)
@csrf_protect
# @ratelimit(key='user', rate=per_day_data_rate, block=True)
def data_api(request, uri, *args, **kwargs):
    return indicator.data_view(request, uri, *args, **kwargs)

@csrf_protect
def little_r_add_data(request, *args, **kwargs):
    return lr.little_r_add_data()

class FakePricer(object):
    def get_price(self, uri):
        return 50.0

pricer = FakePricer()

#@login_required
@csrf_protect
@ratelimit(key='user', rate=per_day_data_rate, block=True)
def fake_buy_view(request, uri, *args, **kwargs):
    user_owns_it = user_owns_data(request.user, uri)
    if user_owns_it:
        return JsonResponse({
            "type": "BuyResult",
            "uri": uri,
            "result": "no_need"
        })

    price = pricer.get_price(uri)
    accounts = request.user.accounts.order_by('priority')
    pay_list = []
    remaining_price = price
    for account in accounts:
        if account.amount >= 0.0:
            this_price = min(remaining_price, account.amount)
            pay_list.append((account, this_price))
            remaining_price -= this_price

            if remaining_price <= 0.0:
                break

    if remaining_price > 0.0:
        return JsonResponse({
            "type": "BuyResult",
            "uri": "uri",
            "result": "failed"
        })

    for account, this_price in pay_list:
        pass
        #try:
          #  sys_account = Account.objects.filter(user=clean_user('admin')).get(type=account.type)
           # transfer(account, sys_account, this_price, cause=uri)
           # user_data_key = get_user_data_key(request.user, uri)
          #  u_d = User_Data(pk=user_data_key)
          #  u_d.save()
          #  return JsonResponse({
          #      "type": "BuyResult",
          #      "uri": uri,
          #      "result": "succeeded"
          #  })
        #except Account.DoesNotExist:
        #    return JsonResponse({
        #        "type": "BuyResult",
        #        "uri": "uri",
        #        "result": "failed"
        #    })


#@login_required
@csrf_protect
@ratelimit(key='user', rate=per_day_data_rate, block=True)
def fake_price_view(request, uri, *args, **kwargs):
    return JsonResponse({
        "type": "PriceResult",
        "uri": uri,
        "result": pricer.get_price(uri)
    })


def get_invite_code_view(request, *args, **kwargs):
    if request.method != 'POST':
        return HttpResponseRedirect('/user/login/')

    p = request.POST
    if p['email']:
       # send_email_to_user(user='admin', context={
        #    'title': u'索要邀请码',
        #    'msg': u'有客户来索要邀请码, 请审核: \n姓名: %s\n邮箱: %s\n电话: %s\n公司: %s\n职务: %s' % (p['name'], p['email'], p['phone'], p['company'], p['position'])
        #})
        return HttpResponseRedirect('/wait_invite/?email=%s' % p['email'])
    else:
        return HttpResponseRedirect('/wait_invite/')

def wait_invite_view(request, *args, **kwargs):
    email = request.GET.get('email', '')
    return render(request, 'fengge/wait_invite.html', context={"email": email})
